package elephant.servers.gameserver.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import elephant.util.DumpUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 
 * @author icecooly
 *
 */
public class GameServerEncoder extends MessageToByteEncoder<ResponseMessage> {
	//
	private static Logger logger=LoggerFactory.getLogger(GameServerEncoder.class);
	//
	private GameServerBodyCodec bodyCodec;
	//
	public GameServerEncoder(GameServerBodyCodec bodyCodec){
		this.bodyCodec=bodyCodec;
	}
	//
    @Override
    protected void encode(ChannelHandlerContext ctx, ResponseMessage msg, ByteBuf out) throws Exception {
    	short serviceIdLength=msg.serviceId==null?0:(short)msg.serviceId.length();
    	short errMsgLength=msg.errMsg==null?0:(short)msg.errMsg.length();
    	int bodyLength=0;
    	byte[] body=null;
    	if(msg.body!=null){
         	body=bodyCodec.encode(msg.bodySerializeType,msg.body);
         	bodyLength=body.length;
        }
    	int totalLength = ResponseMessage.HEAD_LEN+errMsgLength+serviceIdLength+bodyLength;
        ByteBuf buf = Unpooled.buffer(totalLength);
        buf.writeInt(totalLength);
        //Header
        buf.writeInt(msg.requestId);
        buf.writeInt(msg.errCode);
        buf.writeShort(errMsgLength);
        buf.writeShort(msg.bodySerializeType);
        buf.writeLong(System.currentTimeMillis());//timestamp
        buf.writeShort(serviceIdLength);
        //
        if(msg.errMsg!=null){
        	buf.writeBytes(msg.errMsg.getBytes());
        }
        if(msg.serviceId!=null){
        	buf.writeBytes(msg.serviceId.getBytes());
        }
        if(body!=null){
        	buf.writeBytes(body);
        }
        //
        if (logger.isDebugEnabled()) {
            logger.debug("encode msg:{},totalLength:{}",
                    DumpUtil.dump(msg), totalLength);
        }
        out.writeBytes(buf);
    }
}
